#include "bsp_key.h"

void BSP_Key_Init(void)
{
	stc_gpio_cfg_t stcGpioCfg;   
    ///< 打开GPIO外设时钟门控
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); 
    
    ///< 端口方向配置->输入 
    stcGpioCfg.enDir = GpioDirIn;
    ///< 端口上下拉配置-> none (外部10k上拉,按下接地)
    stcGpioCfg.enPu = GpioPuDisable;
    stcGpioCfg.enPd = GpioPdDisable;
    stcGpioCfg.enOD = GpioOdDisable;
	
	///< 端口输入/输出值寄存器总线控制模式配置->AHB
    stcGpioCfg.enCtrlMode = GpioAHB;
	
    Gpio_Init(EVB_KEY1_PORT, EVB_KEY1_PIN, &stcGpioCfg);
	Gpio_Init(EVB_KEY2_PORT, EVB_KEY2_PIN, &stcGpioCfg);
	Gpio_Init(EVB_KEY3_PORT, EVB_KEY3_PIN, &stcGpioCfg);
	Gpio_Init(EVB_KEY4_PORT, EVB_KEY4_PIN, &stcGpioCfg);
	Gpio_Init(EVB_KEY5_PORT, EVB_KEY5_PIN, &stcGpioCfg);
	
}



uint8_t  key_index_find(uint8_t i)
{
	switch(i)
	{
		case 0:
		return KEY1_PRESSED;
		case 1:
		return KEY2_PRESSED;
	    case 2:
		return KEY3_PRESSED; 
		case 3:
		return KEY4_PRESSED;
		case 4:
		return KEY5_PRESSED;		
		default:
			break;
	}
  return 0;
}


/**********************************************************
* 函数名： Key_read(void) 
* 说明：读取按键值.
*	输入参数:void
* 输出参数:定义返回值:最高位为1，则按键按下，最高位为0，则按键弹起
*********************************************************/
uint8_t Key_read(void)
{
  static uint8_t key_state[KEY_TOTALS]; //每一个按键状态暂存值 
  
  uint8_t key_value = 0;//0为无键按下 , 1 :key1   2 key2   3 key3    4 key4
	
  for(uint8_t i = 0;i < KEY_TOTALS; i++)
  {
	  switch(key_state[i]) 
	  {
	    case key_state_0:  //idle
	      if(key_index_find(i)) 
		  	key_state[i] = key_state_1;
	    break;
	                    
	    case key_state_1://消抖
	      if(key_index_find(i)) 
	      	{
		      key_state[i]=key_state_2;//confirm按下	 
			  return key_value = i + 10; 
		    }	  	
	      else 
		  	key_state[i] = key_state_0;
	    break;
	                    
	    case key_state_2://抬起
	      if(0== key_index_find(i))
	      {
	        key_state[i] = key_state_0;			
			  return key_value = i+1;  /*键值不为0,便于处理*/
 	      }
	    break;
		default : break;
	  }
  }
  return key_value; 
}


void Key_scan(void)
{
	uint8_t keyvalue = Key_read();
	if(keyvalue)
	{
		printf("\r\n Key value = %d",keyvalue);
	}
	return;
}





